package com.hll.spring_book.service.user;

import com.hll.spring_book.mapper.user.UserMapper;
import com.hll.spring_book.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2021-03-30 09:07:59
 */
@Service("userService")
public class UserServiceImpl implements UserService {
  @Resource private UserMapper userMapper;

  /**
   * 通过ID查询单条数据
   *
   * @param id 主键
   * @return 实例对象
   */
  @Override
  public User queryById(Integer id) {
    return this.userMapper.queryById(id);
  }

  /**
   * 新增数据
   *
   * @param user 实例对象
   * @return 实例对象
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public User insert(User user) {
    this.userMapper.insert(user);
    return queryById(user.getId());
  }

  /**
   * 修改数据
   *
   * @param user 实例对象
   * @return 实例对象
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public User update(User user) {
    this.userMapper.update(user);
    return this.queryById(user.getId());
  }

  /**
   * 通过主键删除数据
   *
   * @param id 主键
   * @return 是否成功
   */
  @Transactional(
      propagation = Propagation.REQUIRED,
      isolation = Isolation.DEFAULT,
      timeout = 36000,
      rollbackFor = Exception.class)
  @Override
  public boolean deleteById(Integer id) {
    return this.userMapper.deleteById(id) > 0;
  }

  @Override
  public User login(String name, String pwd) {
    // 没必要给mapper 新增一个方法，可以利用现存的方法实现
    User user = new User();
    user.setName(name);
    user.setPassWord(pwd);
    List<User> list = this.userMapper.queryAll(user);
    if (list.size() > 0) return list.get(0);
    return null;
  }

  @Override
  public List<User> queryUsers(User user) {
    return userMapper.queryAll(user);
  }
}
